// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ripple

import (
	"bytes"
	"fmt"
	"math/rand"
	"path"

	"circuit/kit/rh"
	"circuit/kit/rh/ns"
)

func buildErrHelp(name string, id uint64) string {
	return fmt.Sprintf(errHelpFmt, path.Join("/", name), id)
}

const errHelpFmt = `
  This is an error ripple, named "%s", with QID ⟨Q%016x⟩.

  SYNOPSIS

  cat error  # Read a description of the error condition encountered during a
             # prior operation intended to create this directory.
  cat help   # Read this help screen.

` //

func NewError(name, body string) rh.FID {
	ed := &errorDir{
		name: name,
		body: body,
		help: buildErrHelp(name, uint64(rand.Int63())),
	}
	return ns.NewFID(name, ed)
}

// errorDir is an ns.InterfaceDir
type errorDir struct {
	name string
	body string
	help string
}

func (ed *errorDir) Help() rh.FID {
	return ns.RegulateFork(func() ns.UnregulatedFID {
		return ns.NewReaderFID(
			"help",
			runOnClose(bytes.NewReader([]byte(ed.help)), nil),
		)
	})
}

func (ed *errorDir) Error() rh.FID {
	return ns.RegulateFork(func() ns.UnregulatedFID {
		return ns.NewReaderFID(
			ed.name,
			runOnClose(bytes.NewReader([]byte(ed.body)), nil),
		)
	})
}
